define(function(){

    var test = !2,
        search = View.search(),
        myDiagram,
        getUrl = "";
    search.version || (search.version = "v1");
    //
    if(test){
        getUrl = './json/team_ajax.json'
    }

    var Temp = function(name,group){
        var res = Temp.data;
        var tempName = Temp.from;
        if(!res){
            $.ajax({
                url:"./json/team_style.json",
                async:false,
                success:function(result){
                    Temp.data = result;
                    res = result;
                }
            })
        }
        //
        if(group){
            name += tempName == "default" ? "" : "_"+ Temp.from;
            return res.group[group][name];
        }else{
            return res[tempName][name];
        }
    }
    Temp.from = "default";

    var $$ = go.GraphObject.make;  // for more concise visual tree definitions
    var pathMap;
    var mask = (function(){
        var $mask = $('<div id="mask">');
        var $body = $('body');
        $mask.html('<img src="./assets/img/loading.gif" />');
        return {
            open:function(){
                $body.append($mask);
            },
            close:function(){
                $mask.remove();
            }
        }
    }());

    // diagram - 初始化
    function init() {
        if(myDiagram==void 0){
            var config = {
                allowDrop: true,
                "toolManager.hoverDelay": 250,
                //"LinkDrawn": showLinkLabel,  // this DiagramEvent listener is defined below
                //"LinkRelinked": showLinkLabel,
                "linkingTool.direction": go.LinkingTool.ForwardsOnly,  // only draw "from" towards "to"
                "rotatingTool.snapAngleMultiple": 90,
                "rotatingTool.snapAngleEpsilon": 45,
                "animationManager.isEnabled": false,
                "initialContentAlignment": go.Spot.Center,
                "undoManager.isEnabled": true,
                "allowZoom":true,
                "padding":new go.Margin(500,500),
                "isReadOnly":true,
                "scale":.6,
                mouseHover: doHideTips,
                click: doHideTips,
                //"layout":$$(go.TreeLayout, {
                //    angle: 0,
                //    arrangement: go.TreeLayout.ArrangementVertical,
                //    isRealtime: false,
                //    layerSpacing: 80,
                //    setsPortSpot: false,
                //    setsChildPortSpot: false
                //})
            }
            myDiagram = $$(go.Diagram, "myDiagramDiv",config);
            myDiagram.toolManager.linkingTool.temporaryLink.routing = go.Link.Orthogonal;
            myDiagram.toolManager.relinkingTool.temporaryLink.routing = go.Link.Orthogonal;
            //
            pathMap || (pathMap = getPathMap());
            window.myDiagram = myDiagram;
        }

        loop(false);
        myDiagram.startTransaction();
        // diagram - 面板背景
        document.getElementById("sample").style.backgroundColor = Temp("bg");
        // diagram - 元素组件定义

        // define the group template
        var fieldSubTemplate =
            $$(go.Panel, "TableRow",  // this Panel is a row in the containing Table
                {
                    background: "transparent",
                    click:function(){
                        //console.log(1);
                    }
                },
                new go.Binding("portId","",function(row){return row.key+"_row"}),
                $$(go.Panel,"Vertical",
                    {
                        alignment: go.Spot.Left,
                        stretch: go.GraphObject.Horizontal
                    },
                    rowTemplate()
                )
            )

        var fieldSubListTemplate =
            $$(go.Panel, "TableColumn",
                {
                    background: "transparent"
                },
                $$(go.Panel,"Spot",
                    {
                        alignment:go.Spot.TopLeft,
                        margin:15
                    },
                    $$(go.Panel,"Auto",
                        {
                            column:0
                        },
                        $$(go.Shape,
                            {
                                strokeWidth:2,
                                //stroke:"#4dbcd4",
                                fill:null
                            },
                            new go.Binding("stroke", "key",function(o,node){
                                var name = node.part.data.key;
                                return Temp("bkTop",name);
                            })
                        ),
                        $$(go.Panel, "Table",
                            {
                                margin:new go.Margin(12,0),
                                minSize: new go.Size(320, 10),
                                itemTemplate: fieldSubTemplate
                            },
                            new go.Binding("itemArray","child")
                        )
                    ),
                    new go.Binding("portId", "key"),
                    makePort(new go.Binding("portId","key",function(name){return name+"_T"}),"T", go.Spot.TopCenter, true, true),
                    makePort(new go.Binding("portId","key",function(name){return name+"_B"}), "B", go.Spot.BottomCenter, true, true)
                )
            )

        var fieldTemplate =
            $$(go.Panel, "TableRow",  // this Panel is a row in the containing Table
                {
                    background: "transparent",
                    //mouseHover:function(e,node){
                    //    if(myDiagram.scale>0.25){
                    //        e.event.stopPropagation();
                    //        e.event.preventDefault();
                    //        if(node.data.isNouse){
                    //            Dialog.showTips(e,node);
                    //        }else{
                    //            Dialog.hideTips();
                    //        }
                    //    }
                    //
                    //},
                    //click:function(){
                    //    console.log(1);
                    //}
                },
                $$(go.Panel,"Vertical",
                    {
                        alignment: go.Spot.Left,
                        stretch:go.GraphObject.Horizontal
                    },
                    rowTemplate(),
                    $$(go.Panel, "Table",
                        {
                            background:"white",
                            alignment: go.Spot.Left,
                            itemTemplate: fieldSubListTemplate
                        },
                        new go.Binding("itemArray", "child"),
                        new go.Binding("margin", "child",function(arr){
                            if(arr && arr.length>0){
                                return new go.Margin(30,0,30,0);
                            }
                        })
                    )
                ),
                new go.Binding("portId","",function(row){return row.key+"_row"}),
                new go.Binding("background", "",function(row,node){
                    var color = 'transparent';
                    //if(["ParallelGateway","ExclusiveGateway"].indexOf(row.gateway)>-1){
                    //    //color = "#f49731"
                    //}
                    if(row.isNouse) {
                        color = "#8e8e8e"
                    }
                    return color;
                })
            );

        myDiagram.nodeTemplateMap.add("Process",
            $$(go.Node, "Spot",
                { selectionAdorned: false},
                {
                    locationSpot: go.Spot.Center,
                    locationObjectName: "BODY" ,
                    click:function(event,node){
                        doZorder(node);
                    },
                    movable: true,
                    copyable: false,
                    deletable: false
                },
                $$(go.Panel, "Auto",
                    { name: "BODY" },
                    $$(go.Shape, {fill: "white",strokeWidth:3}),
                    $$(go.Panel, "Vertical",
                        $$(go.Panel, "Auto",
                            {
                                stretch: go.GraphObject.Horizontal
                            },
                            $$(go.Shape,
                                { stroke: null },
                                new go.Binding("fill","key",function(name){
                                    return Temp("bkTop",name);
                                })
                            ),
                            $$(go.TextBlock,
                                {
                                    height:24,
                                    alignment: go.Spot.Center,
                                    margin:15,
                                    stroke: "white",
                                    textAlign: "center",
                                    font: "bold 22px sans-serif"
                                },
                                new go.Binding("text", "text"))),
                        //
                        $$(go.Panel, "Auto",
                            {alignment:go.Spot.Left},
                            $$(go.TextBlock,
                                {
                                    height:22,
                                    margin:new go.Margin(10,0,10,10),
                                    stroke: "#a8a8a8",
                                    font: "bold 20px sans-serif"
                                },
                                new go.Binding("text", "",function(node){
                                    return node.subtext?"上序 : " + node.subtext:'';
                                }))
                        ),
                        $$(go.Panel, "Table",
                            {
                                name:"Table",
                                padding:new go.Margin(1.5,1.5,15,1.5),
                                minSize: new go.Size(400, 10),
                                defaultStretch: go.GraphObject.Horizontal,
                                itemTemplate: fieldTemplate
                            },
                            new go.Binding("itemArray", "child")
                        ),
                        $$(go.Panel, "Auto",
                            {alignment:go.Spot.Left},
                            $$(go.TextBlock,
                                {
                                    height:22,
                                    margin:new go.Margin(5,0,15,10),
                                    stroke: "#a8a8a8",
                                    font: "bold 20px sans-serif"
                                },
                                new go.Binding("text", "",function(node){
                                    return node.subtext1?"下序 : " + node.subtext1:'';
                                })
                            ),
                            new go.Binding("visible",'',function(node){
                                return !!node.subtext1;
                            })
                        )
                    )
                ),
                new go.Binding("zOrder"),
                new go.Binding("location", "pos", go.Point.parse).makeTwoWay(go.Point.stringify),
                new go.Binding("portId", "key"),
                makePort(new go.Binding("portId","key",function(name){return name+"_T"}),"T", go.Spot.TopCenter, true, true),
                makePort(new go.Binding("portId","key",function(name){return name+"_B"}),"B", go.Spot.BottomCenter, true, true)
            )
        );

        myDiagram.nodeTemplateMap.add("Start",
            $$(go.Node, "Spot",
                { selectionAdorned: false},
                { locationSpot: go.Spot.Center, locationObjectName: "BODY" },
                $$(go.Panel,"Auto",
                    {
                        name: "BODY",
                        margin:6,
                        background:Temp("bgStart"),
                        alignment: go.Spot.Center
                    },
                    $$(go.Shape,"RoundedRectangle",{
                            desiredSize: new go.Size(400, 80),
                            fill:"transparent",
                            strokeWidth:0
                        }
                    ),
                    $$(go.TextBlock,{
                        margin:10,
                        text:"开始",
                        font: "bold 22px sans-serif",
                        stroke:"white"
                    })
                ),
                new go.Binding("location", "pos", go.Point.parse).makeTwoWay(go.Point.stringify),
                new go.Binding("portId", "key"),
                makePort(new go.Binding("portId","key",function(name){return name+"_T"}),"T", go.Spot.TopCenter, true, true),
                makePort(new go.Binding("portId","key",function(name){return name+"_L"}), "L", go.Spot.LeftCenter, true, true),
                makePort(new go.Binding("portId","key",function(name){return name+"_R"}), "R", go.Spot.RightCenter, true, true),
                makePort(new go.Binding("portId","key",function(name){return name+"_B"}), "B", go.Spot.BottomCenter, true, true)
            )
        );

        myDiagram.nodeTemplateMap.add("End",
            $$(go.Node, "Spot",
                { selectionAdorned: false},
                { locationSpot: go.Spot.Center, locationObjectName: "BODY" },
                $$(go.Panel, "Auto",
                    {
                        name: "BODY",
                        margin:6,
                        background:Temp("bgStart"),
                        alignment: go.Spot.Center
                    },
                    $$(go.Shape,"RoundedRectangle",{
                            desiredSize: new go.Size(400, 80),
                            fill:"transparent",
                            strokeWidth:0
                        }
                    ),
                    $$(go.TextBlock,{
                        margin:10,
                        text:"结束",
                        font: "bold 22px sans-serif",
                        stroke:"white"
                    })
                ),
                new go.Binding("location", "pos", go.Point.parse).makeTwoWay(go.Point.stringify),
                new go.Binding("portId", "key"),
                makePort(new go.Binding("portId","key",function(name){return name+"_T"}),"T", go.Spot.TopCenter, true, true),
                makePort(new go.Binding("portId","key",function(name){return name+"_L"}), "L", go.Spot.LeftCenter, true, true),
                makePort(new go.Binding("portId","key",function(name){return name+"_R"}), "R", go.Spot.RightCenter, true, true),
                makePort(new go.Binding("portId","key",function(name){return name+"_B"}), "B", go.Spot.BottomCenter, true, true)
            )
        );

        myDiagram.linkTemplate =
            $$(go.Link,
                {
                    zOrder:99,
                    routing: go.Link.Orthogonal,
                    curve: go.Link.JumpOver,
                    adjusting: go.Link.Stretch,
                    corner: 10,
                    relinkableFrom: true,
                    relinkableTo: true,
                    reshapable: true,
                    resegmentable: true,
                    selectable: true,
                    toShortLength: -3,
                    toEndSegmentLength: 0
                },
                $$(go.Shape, { isPanelMain: true, stroke: "#b5b5b5", strokeWidth: 10 }),
                $$(go.Shape, { isPanelMain: true, stroke: Temp("link"), strokeWidth: 9 }),
                $$(go.Shape, { isPanelMain: true, name: "PIPE", strokeWidth: 6, stroke: "white", strokeDashArray: [10, 10]}),
                new go.Binding("points","points").makeTwoWay(function(point,node){
                    var arr = [];
                    point.iterator.each(function(o){
                        if(o.J){
                            arr.push(+Number(o.M).toFixed(4))
                            arr.push(+Number(o.N).toFixed(4))
                        }else{
                            arr.push(+Number(o.x).toFixed(4))
                            arr.push(+Number(o.y).toFixed(4))
                        }
                    })
                    return arr;
                }),
                new go.Binding("fromPort","fromPort",function(name){
                    return name;
                }).makeTwoWay(),
                new go.Binding("toPort","toPort",function(name){
                    return name;
                }).makeTwoWay()
            );

        //
        myDiagram.commitTransaction();
        loop(true);
    };

    //  diagram - 业务函数
    function rowTemplate(){
        var $$ = go.GraphObject.make;
        return $$(go.Panel,"Vertical",
            {
                stretch:go.GraphObject.Horizontal,
                alignment: go.Spot.Left
            },
            $$(go.TextBlock,
                {
                    height:18,
                    margin: new go.Margin(0,10,4,10),
                    stretch:go.GraphObject.Horizontal,
                    name:"occupy_pre",stroke:Temp("fontOccupy"),column: 2, font: "16px sans-serif",alignment: go.Spot.Left
                },
                new go.Binding("visible", "",function(row){
                    return !!row.showOccupyPre;
                }),
                new go.Binding("text", "",rowTemplate_occupy_pre)
            ),
            $$(go.Panel,"Auto",
                {
                    stretch:go.GraphObject.Horizontal,
                    alignment: go.Spot.Left
                },
                $$(go.Panel,"Horizontal",
                    {
                        stretch:go.GraphObject.Horizontal,
                        margin: new go.Margin(8,1.5,8,1.5),
                        padding: new go.Margin(0,10,0,10)
                    },
                    new go.Binding("background", "",function(row,node){
                        var color = 'transparent';
                        if(row.isNouse) {
                            //
                        }else if(["ParallelGateway","ExclusiveGateway"].indexOf(row.gateway)>-1){
                            color = Temp("bg"+row.gateway);
                        }else{
                            color = "#ececec";
                        }
                        return color;
                    }),
                    $$(go.Picture,
                        {
                            width:20,
                            height:20,
                            margin:new go.Margin(5,5,5,0),
                            alignment:go.Spot.Bottom
                        },
                        new go.Binding("visible", "",function(node){
                            return ["ParallelGateway","ExclusiveGateway"].indexOf(node.gateway)>-1;
                        }),
                        new go.Binding("source", "",function(node){
                            return Temp("img"+node.gateway);
                        })
                    ),
                    $$(go.TextBlock,
                        {
                            height:20,
                            margin: new go.Margin(6,0,6,0),
                            name:"title", column: 1, font: "bold 18px sans-serif", alignment: go.Spot.Left, fromLinkable: false, toLinkable: false
                        },
                        new go.Binding("stroke", "",function(node){
                            var val = "black";
                            if(node.gateway=="ParallelGateway"){
                                val = Temp("fontParallelGateway");
                            }else if(node.gateway=="ExclusiveGateway"){
                                val = Temp("fontExclusiveGateway");
                            }
                            return val;
                        }),
                        new go.Binding("font", "",function(node){
                            var val = "bold 18px sans-serif";
                            if(["ParallelGateway","ExclusiveGateway"].indexOf(node.gateway)>-1){
                                val = "bold 18px sans-serif";
                            }
                            return val;
                        }),
                        new go.Binding("text", "text",function(name){
                            return " - "+name;
                        })
                    )
                ),
                new go.Binding("portId", "key"),
                makePort(new go.Binding("portId","key",function(name){return name+"_L"}), "L", go.Spot.LeftCenter, true, true),
                makePort(new go.Binding("portId","key",function(name){return name+"_R"}), "R", go.Spot.RightCenter, true, true)
            ),
            $$(go.TextBlock,
                {
                    height:18,
                    margin:new go.Margin(4,10,0,10),
                    stretch:go.GraphObject.Horizontal,
                    name:"occupy_next",stroke:Temp("fontOccupy"),column: 2, font: "16px sans-serif",alignment: go.Spot.Left
                },
                new go.Binding("visible", "",function(row){
                    if(["ParallelGateway","ExclusiveGateway"].indexOf(row.gateway)>-1){
                        return true;
                    }else if(row.isNouse){
                        return false;
                    }else{
                        return true;
                    }
                }),
                new go.Binding("text", "",rowTemplate_occupy_next)
            ),
            new go.Binding("portId", "key",function(name){
                return name+"_parent"
            }),
            new go.Binding("visible", "text",function(text){
                return !!text;
            })
        )
    }
    function rowTemplate_occupy_pre(row){
        return "●  占压 :  "+ (row.occupy_pre===void 0?"":row.occupy_pre);
    }
    function rowTemplate_occupy_next(row){
        var name = "";
        if(["ParallelGateway","ExclusiveGateway"].indexOf(row.gateway)>-1){
            //
        }else{
            name = "●  占压 :  " + (row.occupy_next===void 0?"":row.occupy_next);
        }
        return name;
    }

    function makePort(name, alignName, spot, output, input) {
        var align = go.Spot.Center;
        switch (alignName){
            case "T":
                align = new go.Spot(0.5, 0, 0, -5);
                break;
            case "IT":
                align = new go.Spot(0.5, 0, 0, -10);
                alignName = "T";
                break;
            case "B":
                align = new go.Spot(0.5, 1, 0, 5);
                break;
            case "IB":
                align = new go.Spot(0.5, 1, 0, 10);
                alignName = "B";
                break;
            case "R":
                align = new go.Spot(1, 0.5, 2, 0);
                break;
            case "L":
                align = new go.Spot(0, 0.5, -2, 0);
                break;
        }
        //
        var bindPortId = typeof name == "string" ? (new go.Binding("portId","",function(){return name})) : name;
        var horizontal = ["T","B"].indexOf(alignName)>-1;
        return $$(go.Panel, "Auto",
            {
                alignment: align,
                fromLinkableSelfNode:true,
                fromSpot: spot,
                fromLinkable: output,
                toLinkableSelfNode:true,
                toSpot: spot,
                toLinkable: input,
                cursor: "pointer",
                mouseEnter: function(e, port) {  // the PORT argument will be this Shape
                    if (!e.diagram.isReadOnly){
                        var shape = port.findObject("SHAPE");
                        shape.fill = Temp("link");
                    }
                },
                mouseLeave: function(e, port) {
                    var shape = port.findObject("SHAPE");
                    if(!shape.hasLink){
                        shape.strokeWidth = 0;
                        shape.fill = "transparent";
                    }
                }
            },
            $$(go.Shape,
                {
                    margin: new go.Margin(-1,-1),
                    name: "SHAPE",
                    fill: "transparent",
                    stroke: "#999",
                    strokeWidth:0,
                    width: horizontal ? 40 : 12,  // if not stretching horizontally, just 8 wide
                    height: !horizontal ? 40 : 12,  // if not stretching vertically, just 8 tall
                    spot1: new go.Spot(0, 0, 5, 1),
                    spot2: new go.Spot(1, 1, -5, 1)
                },
                new go.Binding("fill","",function(node,el){
                    if(node.ports.indexOf(alignName)>-1){
                        el.hasLink = true;
                        return Temp("link");
                    }else{
                        return "transparent";
                    }
                })
            ),
            $$(go.TextBlock, new go.Binding("text", "",function(){return " "})),
            new go.Binding("visible","",function(node){
                var hasPort = true;
                //if(node.child){
                //    if(node.category){
                //        //
                //    }else if(/\_\d*\_/.test(node.key)){
                //        //
                //    }else{
                //        hasPort = false;
                //    }
                //}
                return hasPort;
            }),
            bindPortId
        );
    }

    function doHideTips(event){
        Dialog.hideTips();
    }

    function doZorder(node){
        if(node.zOrder>0){return;}
        node.zOrder = 1;
        loop.renderFuns.push(function(){
            myDiagram.nodes.each(function(one){
                myDiagram.model.setDataProperty(one.data,"zOrder",one.key==node.key?1:0);
            });
        })
    }

    function definePathPattern(geostr, color, width, cap) {
        if (typeof name !== 'string' || typeof geostr !== 'string') throw new Error("invalid name or geometry string argument: " + name + " " + geostr);
        if (color === undefined) color = "black";
        if (width === undefined) width = 1;
        if (cap === undefined) cap = "square";
        return go.GraphObject.make(go.Shape,
            {
                geometryString: geostr,
                fill: "transparent",
                stroke: color,
                strokeWidth: width,
                strokeCap: cap
            }
        );
    }
    function getPathMap(){
        // Define a bunch of small Shapes that can be used as values for Shape.pathPattern
        var PathPatterns = new go.Map('string', go.Shape);
        PathPatterns.add("Dot", definePathPattern("M0 0 M8 0 L8.1 0", "gray", 4, "round"));
        PathPatterns.add("Herringbone", definePathPattern("M0 0 L2 2 L0 4  M1.1 0.1 L2.1 2.1 L1.1 4.1 M10 0 L12 2 L10 4","white",1,"round"));
        PathPatterns.add("Sawtooth", definePathPattern("M0 3 L4 0 2 6 6 3"));
        //
        return function(name){
            return PathPatterns.getValue(name);
        }
    }

    function loop(flag) {
        var diagram = myDiagram;
        var handerTime = 500;
        var start = function() {
            var oldskips = diagram.skipsUndoManager;
            diagram.startTransaction("start");
            diagram.skipsUndoManager = true;
            for(var key in loop.funs){
                loop.funs[key]();
            }
            //
            while(loop.renderFuns.length){
                var fn = loop.renderFuns.pop();
                fn();
            }
            //
            diagram.skipsUndoManager = oldskips;
            diagram.commitTransaction("start");
            clearTimeout(loop.hander);
            loop.hander = setTimeout(start,handerTime);
        }
        //
        if(flag){
            loop.hander || start();
        }else{
            loop.hander = clearTimeout(loop.hander);
        }
    }
    loop.funs = {
        links:function(){
            if(myDiagram.scale<0.25){return;}
            myDiagram.links.each(function(link) {
                var shape = link.findObject("PIPE");
                if(shape){
                    var off = shape.strokeDashOffset - 4;
                    shape.strokeDashOffset = (off <= 0) ? 20 : off;
                }
            });
        },
        occupy:function(){
            if(myDiagram.scale<0.25){return;}
            if(!myDiagram.result){return;}
            var arr = myDiagram.result.nodeDataArray;
            var color = Temp("fontOccupy");
            var colorRed = Temp("fontOccupyRed");
            var el,node,data;
            arr.forEach(function(one){
                if(one.group){
                    var $group = myDiagram.findPartForKey(one.group);
                    var data = $group.findPort(one.key+"_row").data;
                    el = void 0;
                    el = $group.findPort(one.key+"_parent").findObject("occupy_pre");
                    if(el){
                        if(one.occupy_pre_valid){
                            el.stroke = color==el.stroke ? colorRed : color;
                        }else{
                            el.stroke = color;
                        }
                        el.text = rowTemplate_occupy_pre(data);
                    }
                    //
                    el = $group.findPort(one.key+"_parent").findObject("occupy_next");
                    if(el){
                        if(one.occupy_next_valid){
                            el.stroke = color==el.stroke ? colorRed : color;
                        }else if(el){
                            el.stroke = color;
                        }
                        el.text = rowTemplate_occupy_next(data);
                    }
                }
            });
        }
    }
    loop.renderFuns = [];

    function load() {
        var url = getUrl || View.baseUrl + "/dgraph/step/queryNew?" + $.param(search);
        //
        mask.open();
        if(!/^v2/.test(search.version)){return;}
        $.getJSON(url,{},function(res){
            mask.close();
            myDiagram.result = res;
            res.linkDataArray = res.linkDataArray.filter(function(v){
                if(v.from && v.to){
                    v.points = v.points.split(",").map(function(v){return Number(v);});
                    return true;
                }else{
                    return false;
                }
            })
            var data = View.teamData(res).teamLinkIcon().data;
            myDiagram.model = go.Model.fromJson(data);
        })
        //
        //clearInterval(load.hander);
        //load.hander = setInterval(function(){
        //    $.getJSON(url,{},function(res){
        //        var linkArr = [];
        //        Array.prototype.push.apply(linkArr,res.linkRel);
        //        myDiagram.nodes.each(function(node){
        //            var data = node.data;
        //            data.child && setVal(data.child,node);
        //        });
        //
        //        function setVal(arr,node){
        //            arr.forEach(function(v){
        //                var one;
        //                v.child && setVal(v.child,node);
        //                if(/^_/.test(v.key)){
        //                    return;
        //                }
        //                if(typeof v.occupy_next == "number"){
        //                    one = View.getOne(linkArr,{from: v.key},true);
        //                    if(one) {
        //                        v.occupy_next = one.occupy;
        //                        v.occupy_next_valid = one.occupy_valid;
        //                    }
        //                }
        //                if(typeof v.occupy_pre == "number"){
        //                    one = View.getOne(linkArr,{to: v.key},true);
        //                    if(one){
        //                        v.occupy_pre = one.occupy;
        //                        v.occupy_pre_valid = one.occupy_valid;
        //                    }
        //                }
        //            });
        //        }
        //    })
        //},5000)
    }

    function save(){
        var data = filterParam();//.replace("class","odid\":\"\",\"pos");
            data.version = search.version;
        data.linkDataArray = data.linkDataArray.filter(function(v){
            v.points = v.points.join(",");
            delete v.uid;
            return v.from && v.to;
        })
        mask.open();
        $.ajax({
            url:View.baseUrl + '/dgraph/step/saveNew',
            type:"put",
            contentType:"application/json",
            data:JSON.stringify(data),
            success:function(res){
                mask.close();
                if(res=="success"){
                    alert("OK");
                }
            },
            error:function(){
                mask.close();
                alert("ERROR");
            }
        })
    }

    function filterParam(){
        var json = myDiagram.model.toJSON().replace("class","pos");
        var result = JSON.parse(json);
        var nodeArr = result.nodeDataArray;
        var res = [];
        nodeArr.forEach(function(v){
            v.child && v.child.forEach(function(v){
                if(!isNouse(v)){
                    saveChild(v);
                    v.category = v.category || v.gateway || "Process"
                    delete v.child;
                    res.push(v);
                }
            });
            delete v.child;
            res.push(v);
        });

        function saveChild(one){// 工序-child
            if(one.child){// 存在子分支
                one.child.forEach(function(v){
                    v.child.forEach(function(vv){
                        vv.category = vv.category || vv.gateway || "Process"
                        if(!isNouse(vv)) {
                            res.push(vv);
                        }
                    });
                });
            }
        }

        function isNouse(one){
            return /^_/.test(one.key);
        }
        //
        result.nodeDataArray = res;
        return result;
    }

    //
    $.API = {
        init:init,
        load:load,
        save:save,
        param:filterParam,
        //
        theme:function(name){
            Temp.from = name;
            init();
        },
        make:function(res){
            if(res){
                typeof res == "object" || (res = localStorage.setItem("team"));
                myDiagram.model = go.Model.fromJson(res);
            }else{
                res = myDiagram.model.toJSON();
                localStorage.setItem("team",res);
                return res;
            }
        }
    }
})